package com.traffic.between.service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.traffic.between.config.BetweenProperties;

import sun.misc.BASE64Encoder;



public class YunLiuServiceImpl {
	private static Logger logger = Logger.getLogger(YunLiuServiceImpl.class);
	public static YunLiuServiceImpl service = new YunLiuServiceImpl();
	
	private static String HOST_ORDER_PATH = BetweenProperties.YUNLIU_ORDER_URL;
	private static String HOST_ORDERSTATUS_PATH = BetweenProperties.YUNLIU_ORDERSTATUS_URL;
	private static String YUNLIU_CUSTID = BetweenProperties.YUNLIU_CUSTID;
	private static String YUNLIU_KEY = BetweenProperties.YUNLIU_KEY;
	
	
	
	public String order(String pkgNo, String phoneNo, String tradeNo) {
		//时间戳
		String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		//请求的参数集合
		Map<String, String> paramsmap = new HashMap<String, String>();
		paramsmap.put("custId", YUNLIU_CUSTID);
		paramsmap.put("shopProductId",pkgNo);
		paramsmap.put("telPhone", phoneNo);
		paramsmap.put("requestNo", tradeNo);
		
		
		String json = new Gson().toJson(paramsmap);
		logger.info("云流订购请求参数信息："+json);
		StringBuffer stringBuffer = new StringBuffer();
		try {

			URL url = new URL(HOST_ORDER_PATH);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoInput(true);
			conn.setDoOutput(true);       
			// Post 请求不能使用缓存    
			conn.setUseCaches(false); 
			conn.setConnectTimeout(30 * 1000);
			conn.setReadTimeout(60 * 1000);
			conn.addRequestProperty("Accept", "*/*");
			conn.addRequestProperty("Content-Type", "text/plain");
			conn.addRequestProperty("timestamp", timestamp);
			conn.addRequestProperty("custid", YUNLIU_CUSTID.trim());
			String text = encryptedDate(YUNLIU_KEY, json);
			OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
			out.write(text);
			out.flush();
			out.close();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
			String responseLine = "";

			while((responseLine = reader.readLine()) != null) {
				stringBuffer.append(responseLine);
			}
			logger.info("云流订购返回参数信息："+stringBuffer.toString()+",该订单号为："+tradeNo);
		} catch (Exception e) {
			logger.info("云流订购请求异常信息："+e.getMessage()+",该订单号为："+tradeNo);
		}
		
		return stringBuffer.toString();
	}

	
	
	
	public String orderStatus(String cstmOrderNo,String suppOrderNo,String phoneNo) {
		StringBuffer stringBuffer = new StringBuffer();
		try {
			//时间戳
			String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			//请求的参数集合
			Map<String, String> paramsmap = new HashMap<String, String>();
			paramsmap.put("custId",YUNLIU_CUSTID.trim());
			paramsmap.put("telPhone", phoneNo);
			paramsmap.put("requestNo",cstmOrderNo);
			paramsmap.put("orderId", suppOrderNo);
			String json =  new Gson().toJson(paramsmap);
			logger.info("云流查询请求参数信息："+json);
	
			URL url = new URL(HOST_ORDERSTATUS_PATH);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoInput(true);
			conn.setDoOutput(true);       
			// Post 请求不能使用缓存    
			conn.setUseCaches(false); 
			conn.setConnectTimeout(30 * 1000);
			conn.setReadTimeout(60 * 1000);
			conn.addRequestProperty("Accept", "*/*");
			conn.addRequestProperty("Content-Type", "text/plain");
			conn.addRequestProperty("timestamp", timestamp);
			conn.addRequestProperty("custid", YUNLIU_CUSTID.trim());
			String text = encryptedDate(YUNLIU_KEY, json);
			OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
			out.write(text);
			out.flush();
			out.close();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
			String responseLine = "";

			while((responseLine = reader.readLine()) != null) {
				stringBuffer.append(responseLine);
			}
			logger.info("云流查询请求返回参数信息："+stringBuffer.toString()+",该订单号为："+cstmOrderNo);
		
		} catch (Exception e) {
			logger.info("订购请求异常："+e.getMessage());

		}
	
		return stringBuffer.toString();
	}

	
	
	




	/**
	 * @Description： 把map转换成json并加密
	 * @param pwd
	 *            密钥
	 * @param paramsJson 要加密的数据JSON数据
	 * @return 已加密的数据
	 * @author: LIZHAOYANG
	 * @since: 2015年6月5日 下午5:37:42
	 */
	public static String encryptedDate(String pwd, String paramsJson)
			throws Exception, NoSuchAlgorithmException, NoSuchPaddingException,
			IllegalBlockSizeException, BadPaddingException,
			UnsupportedEncodingException {
		String result = aesEncrypt(paramsJson, pwd);
		return result;
	}
	public static String aesEncrypt(String content, String password) {
		String ALGO = "AES";
		byte[] result = null;
		try{
			
			byte[] enCodeFormat = password.getBytes();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, ALGO);
			Cipher cipher = Cipher.getInstance(ALGO);// 创建密码器
			byte[] byteContent = content.getBytes("UTF-8");
			cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
			result = cipher.doFinal(byteContent);
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return new BASE64Encoder().encode(result); // 加密

	}
	
	public static void main(String[] args) {
		String json = "{\"code\": 1,\"errorcode\": 200,\"message\": [{\"isPay\": 0,\"orderId\": 100004954}],\"sequence\": \"19665519430549\",\"successcount\": 1,\"trafficShopProduct\": [],\"userInventorylist\": []}";
		JSONObject re = JSONObject.fromObject(json);
		System.out.println(re.get("code"));
		JSONArray  message = re.getJSONArray("message");
		JSONObject res = JSONObject.fromObject(message.get(0));
		System.out.println(res.getInt("isPay"));

	}
}
